package com.yjt.fresh.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.activity.AtyStoreDetail;
import com.yjt.fresh.adpater.AdpRvAtyProductDetailComment;
import com.yjt.fresh.api.ApiGetProductDetail;
import com.yjt.fresh.base.BaseSimpleFragment;
import com.yjt.fresh.bean.BeanProductDetail;
import com.yjt.fresh.bean.MessageEvent;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.CommonsToolsHelper;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.GlideCircleTransform;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import im.delight.android.webview.AdvancedWebView;

/**
 * 商品详情的商品
 * Created by mcc on 2018/6/15.
 */

public class FrgProductDetailProduct extends BaseSimpleFragment {
    @BindView(R.id.banner_app_atyproductdetail_frg_product)
    MZBannerView mBanner;
    @BindView(R.id.rv_app_atyproductdetail_frg_product_comment)
    RecyclerView mRv;
    @BindView(R.id.tvAppAtyProductDetailFrgProductTitle)
    TextView mTvTitle;
    @BindView(R.id.tvAppAtyProductDetailFrgProductNewPrice)
    TextView mTvNewPrice;
    @BindView(R.id.tvAppAtyProductDetailFrgProductOldPrice)
    TextView mTvOldPrice;
    @BindView(R.id.tvAppAtyProductDetailFrgProductSaleQuantity)
    TextView mTvSaleQuantity;
    @BindView(R.id.tvAppAtyProductDetailFrgProductType)
    TextView mTvType;
    @BindView(R.id.rlAppAtyProductDetailFrgProductChooseType)
    RelativeLayout mRlChooseType;
    @BindView(R.id.tvAppAtyProductDetailFrgProductCommentCount)
    TextView mTvCommentCount;
    @BindView(R.id.btnAppAtyProductDetailFrgProductCheckAllComments)
    Button mBtnCheckAllComments;
    @BindView(R.id.tvAppAtyProductDetailFrgProductStoreName)
    TextView mTvStoreName;
    @BindView(R.id.btnAppAtyProductDetailFrgProductToStore)
    Button mBtnToStore;
    @BindView(R.id.tvAppFrgProductDetailNoComment)
    TextView mTvNoComment;
    @BindView(R.id.wbAppFrgProductDetail)
    AdvancedWebView mWebView;
    @BindView(R.id.ivAppFrgProductDetailStoreLogo)
    ImageView mIvStoreLogo;
    private AdpRvAtyProductDetailComment mAdpComment;

    @Override
    protected int getContentView() {
        return R.layout.app_atyproductdetail_frg_product;
    }

    @Override
    protected void initView(Bundle savedInstanceState, View view) {
        ButterKnife.bind(this, view);
        mTvOldPrice.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );
    }

    @Override
    protected void initEvents() {
        initRV();
        getData();
        initClick();
        //注册eventbus用于跳转店铺
        EventBus.getDefault().register(this);
    }

    public void setGoodsType(String type){
        mTvType.setText(type);
    }
    private void initRV() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        mRv.setLayoutManager(layoutManager);
        mRv.setHasFixedSize(true);
        mRv.setNestedScrollingEnabled(false);
        List<BeanProductDetail.EVALUATELISTBean> list = new ArrayList<>();
        mAdpComment = new AdpRvAtyProductDetailComment(R.layout.app_recycle_item_comment, list);
        mRv.setAdapter(mAdpComment);
    }
    public class BannerViewHolder implements MZViewHolder<String> {

        private ImageView mIV;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.app_banner_item_frg_productdetail, null);
            mIV = view.findViewById(R.id.ivAppBannerItemFrgProductDetail);
            ViewGroup.LayoutParams params = mIV.getLayoutParams();
            params.width = CommonsToolsHelper.getWindowWidth(mContext);
            params.height = CommonsToolsHelper.getWindowWidth(mContext);
            mIV.setLayoutParams(params);
            return view;
        }

        @Override
        public void onBind(Context context, int position, String url) {
            // 数据绑定
            Glide.with(mContext).load(url).placeholder(R.mipmap.image_default).into(mIV);
        }
    }

    private BeanProductDetail mBeanProductDetail;
    HttpOnNextListener<BeanProductDetail> mProductDetailListener = new HttpOnNextListener<BeanProductDetail>() {
        @Override
        public void onNext(BeanProductDetail beanProductDetail) {
            mBeanProductDetail = beanProductDetail;
            MessageEvent messageEvent = new MessageEvent();
            messageEvent.setRecode(MyConstants.PRODUCT_DETAIL_CONTENT);
            messageEvent.setMsg(beanProductDetail.getCONTENT());
            EventBus.getDefault().post(messageEvent);
            EventBus.getDefault().post(beanProductDetail);
            mBanner.setPages(beanProductDetail.getImgList(), new MZHolderCreator<BannerViewHolder>() {
                @Override
                public BannerViewHolder createViewHolder() {
                    return new BannerViewHolder();
                }
            });
            if (beanProductDetail.getEVALUATELIST().size() > 0) {
                mAdpComment.setNewData(beanProductDetail.getEVALUATELIST());
            }else {
                mTvNoComment.setVisibility(View.VISIBLE);
                mBtnCheckAllComments.setVisibility(View.GONE);
            }
            bindView(beanProductDetail);
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void bindView(BeanProductDetail beanProductDetail) {

        String html = "";
        try {
            Document doc = Jsoup.parse(beanProductDetail.getCONTENT());
            Elements elements = doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width", "100%").attr("height", "auto");
            }

            html = doc.toString();
        } catch (Exception e) {
            html = beanProductDetail.getCONTENT();
        }
        mWebView.loadHtml(html);

        mTvTitle.setText(beanProductDetail.getTITLE());
        mTvCommentCount.setText("商品评价（"+ beanProductDetail.getEVALUATE_COUNT()+"）");
        mTvNewPrice.setText(beanProductDetail.getDISPLAY_SINGLE_PRICE());
        mTvOldPrice.setText("¥  "+ beanProductDetail.getDISPLAY_PRICE());
        mTvSaleQuantity.setText("已销"+ (beanProductDetail.getGROUP_COUNT() == null ? "0" : beanProductDetail.getGROUP_COUNT()));
        mTvStoreName.setText(beanProductDetail.getSTORE_NAME());
        Glide.with(mContext).load(beanProductDetail.getSTORE_LOGO_IMG()).bitmapTransform(new GlideCircleTransform(mContext)).placeholder(R.mipmap.f1_ic_06).into(mIvStoreLogo);

        if ("1".equals(beanProductDetail.getChildgoodsList().get(0).getGOODS_SPEC_TYPE())){
            mRlChooseType.setVisibility(View.GONE);
        }else {
            mRlChooseType.setVisibility(View.VISIBLE);
        }
    }

    private void getData(){
        String goodsID = getArguments().getString(MyConstants.GOODS_ID);
        ApiGetProductDetail apiGetProductDetail = new ApiGetProductDetail(mProductDetailListener,mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        map.put("GOODS_ID",goodsID);
        if (PreferenceManager.getInstance().getIsLogin()){
            map.put("USER_ID",PreferenceManager.getInstance().getUserInfo().getAPPUSER_ID());
        }
        apiGetProductDetail.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetProductDetail);
    }
    private void initClick(){
        mRlChooseType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setRecode(MyConstants.CHOOSE_GOODS_TYPE);
                EventBus.getDefault().post(messageEvent);
            }
        });

        mBtnCheckAllComments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setRecode(MyConstants.TO_PRODUCT_COMMENT);
                EventBus.getDefault().post(messageEvent);
            }
        });

        mBtnToStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                go2StoreDetail();
            }
        });
    }

    private void go2StoreDetail() {
        Intent intent = new Intent(mContext, AtyStoreDetail.class);
        intent.putExtra(MyConstants.STORE_ID,mBeanProductDetail.getSTORE_ID());
        intent.putExtra(MyConstants.STORE_NAME,mBeanProductDetail.getSTORE_NAME());
        intent.putExtra(MyConstants.STORE_LOGO,mBeanProductDetail.getSTORE_LOGO_IMG());
        intent.putExtra(MyConstants.STORE_LOCATION,mBeanProductDetail.getSTORE_LATITUDE_LONGITUDE());
        intent.putExtra(MyConstants.STORE_PHONE,mBeanProductDetail.getSTORE_TEL());
        startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent data) {
        if (data.getRecode() == MyConstants.TO_STORE){
            if (mBeanProductDetail != null){
                go2StoreDetail();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
